import axios from "axios";
import type { InternalAxiosRequestConfig, AxiosResponse } from "axios";
import { useLoginStore } from "../store/loginStore";
import { message } from "ant-design-vue";

export interface ResultDTO<T> {
  code: number;
  msg: string;
  data: T;
}

export enum HTTP_STATUS {
  SUCCESS = 200, //成功

  BAD_REQUEST = 400, //请求参数不正确
  UNAUTHORIZED = 401, //账号未登录
  FORBIDDEN = 403, //没有操作权限
  NOT_FOUND = 404, //请求未找到
  METHOD_NOT_ALLOWED = 405, //请求方法不正确
  CONFLICT = 409, //请求资源冲突
  LOCKED = 432, //请求失败，请稍后再试
  TOO_MANY_REQUESTS = 429, //请求过于频繁，请稍后再试

  INTERNAL_SERVER_ERROR = 500, //服务器内部错误
  NOT_IMPLEMENTED = 501, //功能未实现
  ERROR_CONFIGURATION = 502, //错误配置项

  REPEATED_REQUESTS = 900, //请求重复，请稍后再试
  UNKNOWN = 502, //未知错误
}

const service = axios.create({
  baseURL: "/api",
  timeout: 10000000,
  withCredentials: false,
});

service.interceptors.request.use((config: InternalAxiosRequestConfig<any>) => {
  const loginStore = useLoginStore();
  if (loginStore.isAuthenticated()) {
    config.headers.Authorization = "Bearer " + loginStore.$state.token;
  }
  return config;
});

service.interceptors.response.use(
  (res: AxiosResponse<any>) => {
    const resultData : ResultDTO<any> = res.data
    const loginStore = useLoginStore();
    if (resultData.code === HTTP_STATUS.UNAUTHORIZED) {
      loginStore.removeToken();
      message.warn("请进行登录后再操作");
    } else if (resultData.code === HTTP_STATUS.FORBIDDEN) {
      message.error(resultData.msg);
    } else if (resultData.code !== HTTP_STATUS.SUCCESS) {
      message.error(resultData.msg);
    }
    if (res.headers.authorization) {
      loginStore.setToken(res.headers.authorization)
    }
    res.data.status = resultData.code
    return res.data;
  },
  (error) => {
    message.error("接收响应时发生错误: " + error.message);
    return Promise.reject(error.message);
  }
);


export default service;
